package cn.codergege.demo.config.conversion

import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.MessageSource
import org.springframework.format.Formatter
import org.springframework.stereotype.Component

@Component
class DateFormatter: Formatter<Date> {
    private val log = LoggerFactory.getLogger(javaClass)

    @Autowired
    lateinit var messageSource: MessageSource

    @Throws(ParseException::class)
    override fun parse(text: String, locale: Locale): Date {
        val sdf = createDateFormat(locale)
        return sdf.parse(text)
    }

    override fun print(date: Date, locale: Locale): String {
        val sdf = createDateFormat(locale)
        return sdf.format(date)
    }

    private fun createDateFormat(local: Locale): SimpleDateFormat {
        // 1) 根据 页面的 local 去 messages_zh_CN.properties 或 messages_en_US.properties 中去找
        // 2) 没找到对应的 key, 就去 messages.properties 中找
        // 3) 还没找到, 就用 yyyy-MM-dd 这个默认值
        val format = messageSource.getMessage("date.format", null, "yyyy-MM-dd", local)
        val sdf = SimpleDateFormat(format)
        log.info("----> Fomatter runs... local is {}", local.country)
        return sdf
    }
}
